package com.qf.controller;

import com.qf.domain.Questions;
import com.qf.service.QuestionsService;
import com.qf.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/ques")
public class QuestionsController {
    @Autowired
    private QuestionsService questionsService;

    @GetMapping("/list")
    public ResultVO selectAll(@RequestParam(defaultValue = "1")Integer page,
                              @RequestParam(defaultValue = "5")Integer size){
        ResultVO resultVO=new ResultVO();
        List<Questions> list = questionsService.selectAll(page, size);
        if (list!=null){
            resultVO.setData(list);
            return resultVO;
        }else {
            resultVO.setCode(500);
            resultVO.setMsg("查询失败");
            return resultVO;
        }
    }
    @PostMapping("/insertadd")
    public ResultVO insertadd(@Valid Questions questions, BindingResult bindingResult){
        ResultVO resultVO=new ResultVO();
        if (bindingResult.hasErrors()){
            resultVO.setCode(500);
            resultVO.setMsg(bindingResult.getFieldError().getDefaultMessage());
            return resultVO;
        }else {
            questions.setAnswerCount(0);
            questions.setLastModified(new Date());
            int i=questionsService.insertadd(questions);
            if (i!=1){
                resultVO.setMsg("添加失败");
                resultVO.setCode(500);
                return resultVO;
            }else {
                return resultVO;
            }
        }

    }
}
